print("读取CSV文件")
print("读取CSV文件，包含文件头")
import csv
with open("files/csv001.csv","r",encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
print("读取CSV文件，不包含文件头")
with open("./files/csv001.csv","r",encoding="utf-8") as file:
    reader = csv.reader(file)
    # 因为reader是迭代器，所以使用next方法将第一个元素过滤掉
    header = next(reader)
    print("消息头是：")
    print(header)
    print("遍历消息体：")
    for row in reader:
        print(row)

print("读取CSV文件，并将每一行元素和表头结合，封装成字典")
with open(file="./files/csv001.csv",mode="r",encoding="utf-8") as file:
    reader = csv.reader(file)
    header = next(reader)
    res_list=[]
    for row in reader:
        res_list.append(dict(zip(header,row)))
for res in res_list:
    print(res)

print("写入CSV文件")
print("将二维数组写入CSV文件，其中每一个数组元素是一行")
data=[["name","age"],["zhangsan",30],["lisi",31],["wangwu",26],["zhaoliu",27]]
# with open(file="./files/csv002.csv",mode="a",encoding="utf-8") as file:
with open(file="./files/csv002.csv",mode="w",encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(data)

print("将一维数据写入CSV文件")
data2=["田七",33]
# with open(file="./files/csv003.csv",mode="a",encoding="utf-8") as file:
with open(file="./files/csv003.csv",mode="w",encoding="utf-8",newline="") as file:
    writer = csv.writer(file)
    writer.writerow(data)
    writer.writerow(data2)
print("===========")
with open(file="./files/csv002.csv",mode="r",encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        # print(type(row))
        print(row)

print("读取json文件")
import json
with open(file="./files/json001.json",mode="r",encoding="utf-8") as file:
    data = json.load(file)
    print(type(data))
    print(data)

# with open(file="./files/json002.json",mode="a",newline="",encoding="utf-8") as file:
with open(file="./files/json002.json",mode="w",newline="",encoding="utf-8") as file:
    json.dump(data,file,ensure_ascii=False)

respond="{'username': 'zhangsan', 'age': 23, 'score': {'chanese': 100, 'math': 120}, 'food': ['大米', '馒头'], 'otherInfo': [{'brothers': ['lisi', 'wangwu']}, {'sisters': ['lily', 'lucy']}]}"
# respond_list=[respond,respond]
respond_list=[[respond],[respond]]
with open(file="./files/csv003.csv",mode="a",encoding="utf-8",newline="") as file:
    writer = csv.writer(file)
    # writer.writerow(respond_list)
    writer.writerows(respond_list)